package net.zjitc.controller;

import net.zjitc.pojo.Admin;
import net.zjitc.service.AdminService;
import net.zjitc.utils.APIResponse;
import net.zjitc.utils.JwtUtil;
import net.zjitc.utils.MD5WithSaltUtil;
import net.zjitc.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("/admin")

public class AdminController {
    @Autowired
    private AdminService adminService;



    @PostMapping("login")
    @CrossOrigin(origins = "*")
    @ResponseBody
    public APIResponse<Token> login(@RequestBody Admin admin){
        Admin user=adminService.findAdmin(admin.getUsername(),admin.getPassword());
        APIResponse<Token> apiResponse = new APIResponse<>();
        if(user!=null){
            String token = JwtUtil.generateToken(user.getUsername());
            apiResponse.ok("登录成功",new Token(token));
            return apiResponse;
        }else{
            apiResponse.error(1000,"用户名错误",null);
            return apiResponse;
        }
    }
    @GetMapping("admin")
    @CrossOrigin(origins = "*")
    @ResponseBody
    public APIResponse<Admin> admin(){
        Admin user=adminService.admin();
        user.setAvatar("http://localhost:8080/"+user.getAvatar());
        APIResponse<Admin> apiResponse = new APIResponse<>();
        apiResponse.ok("用户查询成功",user);
        return apiResponse;
    }
    @PostMapping("changeAvatar")
    @CrossOrigin(origins = "*")
    @ResponseBody
    public APIResponse<String> changeAvatar(@RequestBody Map<String,String> request){
        String avatar = request.get("avatar");
        System.out.println(avatar);
        adminService.changeAvatar(avatar);
        APIResponse<String> apiResponse = new APIResponse<>();
        apiResponse.ok("修改成功",null);
        return apiResponse;
    }
    @PostMapping("changePassword")
    @CrossOrigin(origins = "*")
    @ResponseBody
    public APIResponse<String> changePassword(@RequestBody Map<String,String> request){
        String password = request.get("password");
        adminService.changePassword(password);
        APIResponse<String> apiResponse = new APIResponse<>();
        apiResponse.ok("修改成功",null);
        return apiResponse;
    }
}
